package br.com.binding.rebind.template;

import br.com.binding.rebind.ListenerTemplate;

import com.google.gwt.core.ext.typeinfo.JField;
import br.com.binding.client.bind.annotations.TextBind;
import br.com.binding.client.bind.annotations.values.WhenText;

public class TextBindListenerTemplate implements ListenerTemplate {
    
  protected static String nl;
  public static synchronized TextBindListenerTemplate create(String lineSeparator)
  {
    nl = lineSeparator;
    TextBindListenerTemplate result = new TextBindListenerTemplate();
    nl = null;
    return result;
  }

  public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
  protected final String TEXT_1 = "addKeyboardListener(new com.google.gwt.user.client.ui.KeyboardListenerAdapter() {" + NL + "\t\t        \tpublic void onKeyUp(com.google.gwt.user.client.ui.Widget sender, char keyCode, int modifiers) {";
  protected final String TEXT_2 = "addKeyboardListener(new com.google.gwt.user.client.ui.KeyboardListenerAdapter() {" + NL + "                \t\tpublic void onKeyDown(com.google.gwt.user.client.ui.Widget sender, char keyCode, int modifiers) {";
  protected final String TEXT_3 = "addChangeListener(new com.google.gwt.user.client.ui.ChangeListener() {" + NL + "\t\t\t\tpublic void onChange(com.google.gwt.user.client.ui.Widget sender) {";
  protected final String TEXT_4 = NL + "\t\t\t\t\t";
  protected final String TEXT_5 = ".";
  protected final String TEXT_6 = "(";
  protected final String TEXT_7 = ".getText());" + NL + "                            }" + NL + "                        });";

    /* (non-javadoc)
     * @see IGenerator#generate(Object)
     */
    public String generate(Object argument)
  {
    final StringBuffer stringBuffer = new StringBuffer();
    
    JField field = (JField)argument;
    TextBind bind = field.getAnnotation(TextBind.class);
    String model = bind.model();
    String name = bind.name();
    String fieldName = field.getName();
    String setMethod = "set" + name.substring(0,1).toUpperCase() + name.substring(1);
    WhenText when = bind.when();
 
    
 	  					switch(when){
 								case ON_KEY_UP: {
 						
    stringBuffer.append(TEXT_1);
    	
                            		break;
	                            }
	                            case ON_KEY_DOWN:{
                            
    stringBuffer.append(TEXT_2);
    
                            		break;
                            	}
                            	default: {
                            
    stringBuffer.append(TEXT_3);
    
									break;
								}
							}
							
    stringBuffer.append(TEXT_4);
    stringBuffer.append(model);
    stringBuffer.append(TEXT_5);
    stringBuffer.append(setMethod);
    stringBuffer.append(TEXT_6);
    stringBuffer.append(fieldName);
    stringBuffer.append(TEXT_7);
    return stringBuffer.toString();
  }
} 